package org.jeecg.glr.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.jeecg.common.constant.SysConstant;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SysUtil;
import org.jeecg.glr.entity.GlrSensor;
import org.jeecg.glr.entity.GlrSensorData;
import org.jeecg.glr.iframe.service.IGlrIframeVideoMonitoringService;
import org.jeecg.glr.mapper.GlrSensorMapper;
import org.jeecg.glr.service.IGlrLightPoleDeviceService;
import org.jeecg.glr.service.IGlrSensorDataService;
import org.jeecg.glr.service.IGlrSensorService;
import org.jeecg.glr.util.GLRConstant;
import org.jeecg.netty.SenSorConfigConsts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 传感器
 * @Author: jeecg-boot
 * @Date:   2020-02-11
 * @Version: V1.0
 */
@Service
public class GlrSensorServiceImpl extends ServiceImpl<GlrSensorMapper, GlrSensor> implements IGlrSensorService {

    @Resource
    GlrSensorMapper glrSensorMapper;
    @Autowired
    private RedisUtil redisUtil;


    @Resource
    IGlrSensorDataService glrSensorDataService;

    @Autowired
    private IGlrLightPoleDeviceService glrLightPoleDeviceService;


    @Autowired
    private IGlrIframeVideoMonitoringService glrIframeVideoMonitoringService;

    @Override
    public void saveEntity(GlrSensor glrSensor){
        glrSensorMapper.insert(glrSensor);
        glrLightPoleDeviceService.dataProecss(glrSensor,GLRConstant.GLR_LIGHT_POLE_DEVICE_TYPE_ADD);
        redisUtil.putMap(GLRConstant.SENSOR_CODE_REDIS,glrSensor.getCode(), SysUtil.getUserInfo().getSysCompanyCode());
    }
    @Override
    public void updateEntityById(GlrSensor glrSensor){
        glrLightPoleDeviceService.dataProecss(glrSensor,GLRConstant.GLR_LIGHT_POLE_DEVICE_TYPE_EDIT);
        glrSensorMapper.updateById(glrSensor);
        redisUtil.putMap(GLRConstant.SENSOR_CODE_REDIS,glrSensor.getCode(), SysUtil.getUserInfo().getSysCompanyCode());
    }
    @Override
    public void removeEntityById(String id){
        GlrSensor glrSensor=glrSensorMapper.selectById(id);
        glrSensorMapper.deleteById(id);
        glrLightPoleDeviceService.dataProecss(glrSensor,GLRConstant.GLR_LIGHT_POLE_DEVICE_TYPE_DELETE);
    }

    @Override
    public void removeEntityByIds(List<String> asList){
        for(String stId:asList){
            GlrSensor glrSensor=glrSensorMapper.selectById(stId);
            glrSensorMapper.deleteById(stId);
            glrLightPoleDeviceService.dataProecss(glrSensor,GLRConstant.GLR_LIGHT_POLE_DEVICE_TYPE_DELETE);
        }
    }


    @Override
    public GlrSensorData getGlrSensorOne(String type, HttpServletRequest request)  {
        String sql="select * from glr_sensor_data where 1=1   ORDER BY create_time desc LIMIT 0,1";
        return glrSensorMapper.getGlrSensorOne(sql);
    }

    @Override
    public List<String> getGlrSensorStatus() {
        String sql="select status from glr_sensor where 1=1";
       /* if(!SysUtil.getUserInfo().getUserType().equals(SysConstant.SYS_USER_TYPE_ADMIN)){
                sql=sql+" and sys_company_code='"+SysUtil.getUserInfo().getSysCompanyCode()+"'";
        }*/
        return glrSensorMapper.getGlrSensorStatus(sql);
    }

    @Override
    public GlrSensorData getGlrSensorByCodeOne(String code) {
        String sql="select * from glr_sensor_data where 1=1  and sensor_code='"+code+"' ORDER BY create_time desc LIMIT 0,1";
        return glrSensorMapper.getGlrSensorOne(sql);
    }

    @Override
    public GlrSensor getGlrSensorByCode(String code) {
       return glrSensorMapper.getGlrSensorByCode(code);
    }

    @Override
    public void dealData(ByteBuf buf, Channel channel) {
        GlrSensorData  data = new GlrSensorData();
        Short code= buf.readUnsignedByte();//01
       if( redisUtil.getMap(SenSorConfigConsts.SENSOR_CODE_REDIS,String.valueOf(code))==null){
           return;
       }
        saveSenSorCode(code,channel);
        int biaoshi=buf.readUnsignedByte();
        int length=buf.readByte();
        double wd=buf.readUnsignedShort()/10;
        double sd=buf.readUnsignedShort()/10;
        double pm25=buf.readUnsignedShort();
        buf.readUnsignedShort();
        buf.readUnsignedShort();
        double c02=buf.readUnsignedShort();
        data.setSensorCode(String.valueOf(code));
        data.setHumidity(sd);
        data.setTemperature(wd);
        data.setPm25(pm25);
        data.setPm10(c02);
        data.setCreateTime(new Date());
        glrSensorDataService.save(data);
    }

    @Override
    public List<GlrSensor> getSenSorAll() {
        List<GlrSensor> list= glrSensorMapper.getSenSorAll();
        for (GlrSensor sensor :
                list) {
            redisUtil.putMap(SenSorConfigConsts.SENSOR_CODE_REDIS,sensor.getCode(),sensor.getSysCompanyCode());
        }
        return list;
    }
    @Override
    public void removeOffLineGataWay(ChannelHandlerContext ctx) {
        try
        {
            if(SenSorConfigConsts.senSorchannelIdMap.get(ctx.channel().id())!=null) {
                short key	=Short.parseShort(SenSorConfigConsts.senSorchannelIdMap.get(ctx.channel().id()).toString());
                //移除掉线的channel
                ctx.channel().close();
                SenSorConfigConsts.senSorchannelMap.remove(key);
                SenSorConfigConsts.senSorchannelIdMap.remove(ctx.channel().id());
                String sql = "update glr_sensor set status='"+GLRConstant.YN_N+"' where code='"+key+"'";
                System.out.println(sql);
                glrSensorMapper.getGlrSensorStatus(sql);
            }
        }
        catch (RuntimeException e)
        {
            e.printStackTrace();
        }

    }
    public  void saveSenSorCode(Short key, Channel channel)
    {
        //判断设备是否已经连接
        if(SenSorConfigConsts.senSorchannelMap.get(key) == null)
        {
            SenSorConfigConsts.senSorchannelMap.put(key, channel);
            SenSorConfigConsts.senSorchannelIdMap.put(channel.id(), key);
            String sql = "update glr_sensor set update_Time=now(), status='"+GLRConstant.YN_Y+"' where code='"+key+"'";
            glrSensorMapper.getGlrSensorStatus(sql);
        }
        else
        {
            //如果已连接
            Channel ch = SenSorConfigConsts.senSorchannelMap.get(key);
            // 判断断开连接以后重新覆盖channel
            if(!ch.id().toString().equals(channel.id().toString()))
            {
                SenSorConfigConsts.senSorchannelMap.put(key, channel);
                SenSorConfigConsts.senSorchannelIdMap.put(channel.id(), key);
            }
        }
    }

    @Override
    public void intiSenSorAll() {
        glrSensorMapper.initSenSor();
        List<GlrSensor> list= glrSensorMapper.getSenSorAll();
        for (GlrSensor sensor :
                list) {
            redisUtil.putMap(SenSorConfigConsts.SENSOR_CODE_REDIS,sensor.getCode(),sensor.getSysCompanyCode());
        }
    }


}
